import React, { Component } from 'react';
import Web3 from 'web3';
import cryptoZombiesABI from '../cryptozombies_abi';
import { BrowserRouter as Router, Route, Link, withRouter } from "react-router-dom";
import { message } from 'antd';
import './Connect.css';


//const web3 = new Web3(new Web3.providers.WebsocketProvider("wss://mainnet.infura.io/ws"));
let web3js, cryptoZombies, userAccount;
class Connect extends Component {
    constructor(props) {
        super(props);
        this.state = {
            account: '',
        };
    }
    async handleConnect() {
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        console.log('handleClick', accounts[0])
        if (accounts[0]) {
            message.success('已连接');
            this.props.history.push('/list')
        }
        window.ethereum.on('accountsChanged', function (accounts) {
            console.log('accountsChanged', accounts)
            // Time to reload your interface with accounts[0]!
        });
    };
    componentDidMount() {
        // setTimeout(() => {
        //     if (window.ethereum.selectedAddress) {
        //         console.log('222222', window.ethereum.selectedAddress)
        //     } else {
        //         console.log('33322', window.ethereum.selectedAddress)
        //     }
        // }, 100)
        
        // 检查web3是否已经注入到(Mist/MetaMask)
        if (typeof web3 !== 'undefined') {
            // 使用 Mist/MetaMask 的提供者
            //web3js = new Web3(window.web3.currentProvider);
            // console.log('web3js', web3js)
        } else {
            // 处理用户没安装的情况， 比如显示一个消息
            // 告诉他们要安装 MetaMask 来使用我们的应用
            // console.log('web3js111')
        }

          // 现在你可以启动你的应用并自由访问 Web3.js:
        //this.startApp()
    }
    startApp() {
        const that = this;
        var cryptoZombiesAddress = "0x6428Fb6A488354FC3B0032FFaF579E5745810548";
        cryptoZombies = new web3js.eth.Contract(cryptoZombiesABI, cryptoZombiesAddress);
        console.log('cryptoZombies', window.web3)
        const accountInterval = setInterval(function() {
          // Check if account has changed
          if (window.web3.eth.accounts[0] !== userAccount) {
            userAccount = window.web3.eth.accounts[0];
            // Call a function to update the UI with the new account
            that.getZombiesByOwner(userAccount)
            .then(res => {
                console.log('res', res)
                that.displayZombies(res)
            }).catch(e => {
                console.log('eeee', e)
            });
          }
        }, 100);
    }
    displayZombies(ids) {
        console.log('ids', ids)
        this.refs.zombies.empty();
        for (var id in ids) {
          // Look up zombie details from our contract. Returns a `zombie` object
          this.getZombieDetails(id).then(function(zombie) {
            // Using ES6's "template literals" to inject variables into the HTML.
            // Append each one to our #zombies div
            this.refs.zombies.append(`<div class="zombie">
              <ul>
                <li>Name: ${zombie.name}</li>
                <li>DNA: ${zombie.dna}</li>
                <li>Level: ${zombie.level}</li>
                <li>Wins: ${zombie.winCount}</li>
                <li>Losses: ${zombie.lossCount}</li>
                <li>Ready Time: ${zombie.readyTime}</li>
              </ul>
            </div>`)
          })
        }
    }
    createRandomZombie(name) {
        // This is going to take a while, so update the UI to let the user know
        // the transaction has been sent
        this.refs.txStatus.text("Creating new zombie on the blockchain. This may take a while...");
        // Send the tx to our contract:
        return cryptoZombies.methods.createRandomZombie(name)
        .send({ from: userAccount })
        .on("receipt", function(receipt) {
          this.refs.txStatus.text("Successfully created " + name + "!");
          // Transaction was accepted into the blockchain, let's redraw the UI
          this.getZombiesByOwner(userAccount).then(this.displayZombies());
        })
        .on("error", function(error) {
          // Do something to alert the user their transaction has failed
          this.refs.txStatus.text(error);
        });
    };
    feedOnKitty(zombieId, kittyId) {
        this.refs.txStatus.text("Eating a kitty. This may take a while...");
        return cryptoZombies.methods.feedOnKitty(zombieId, kittyId)
        .send({ from: userAccount })
        .on("receipt", function(receipt) {
          this.refs.txStatus.text("Ate a kitty and spawned a new Zombie!");
          this.getZombiesByOwner(userAccount).then(this.displayZombies());
        })
        .on("error", function(error) {
          this.refs.txStatus.text(error);
        });
    };
    levelUp(zombieId) {
        this.refs.txStatus.text("Leveling up your zombie...");
        return cryptoZombies.methods.levelUp(zombieId)
        .send({ from: userAccount, value: window.web3.utils.toWei("0.001", "ether") })
        .on("receipt", function(receipt) {
          this.refs.txStatus.text("Power overwhelming! Zombie successfully leveled up");
        })
        .on("error", function(error) {
          this.refs.txStatus.text(error);
        });
    }
    getZombieDetails(id) {
        return cryptoZombies.methods.zombies(id).call()
    }
    zombieToOwner(id) {
        return cryptoZombies.methods.zombieToOwner(id).call()
    }
    getZombiesByOwner(owner) {
        console.log('getZombiesByOwner', owner, cryptoZombies.methods)
        return cryptoZombies.methods.getZombiesByOwner(owner).call()
    }
    handleClick() {
        const transactionParameters = {
          nonce: '0x00', // ignored by MetaMask
          gasPrice: '0x09184e72a000', // customizable by user during MetaMask confirmation.
          gas: '0x2710', // customizable by user during MetaMask confirmation.
          to: window.ethereum.selectedAddress, // Required except during contract publications.
          from: window.ethereum.selectedAddress, // must match user's active address.
          value: '0x00', // Only required to send ether to the recipient from the initiating external account.
          data:
            '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', // Optional, but used for defining smart contract creation and interaction.
          chainId: 3, // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
        };
        // txHash is a hex string
        // As with any RPC call, it may throw an error
        console.log('transactionParameters', transactionParameters)
        const txHash = window.ethereum.request({
          method: 'eth_sendTransaction',
          params: [transactionParameters],
        }).then(function (result) {
            console.log(result)
          // The result varies by method, per the JSON RPC API.
          // For example, this method will return a transaction hash on success.
        })
        .catch(function (reason) {
            console.log(reason)
         // Like a typical promise, returns a reason on rejection.
        });
    }
    render() {
        // console.log('4442', window.ethereum.selectedAddress)
        return (
            <div>
                <div className="connect" onClick={() => this.handleConnect()}>
                    连接
                </div>
                {// <div className="connect" onClick={() => this.handleClick()}>
                //     Connect1
                // </div>
            }
                <div ref="txStatus"></div>
                <div ref="zombies"></div>
            </div>
        )
    }
};

export default withRouter(Connect);
